// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Data.Common;
using JetBrains.Annotations;
using Oracle.ManagedDataAccess.Client;

namespace SnapObjects.Data.Oracle
{
    public class OracleDoubleTypeMapping : OracleTypeMapping
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="OracleDoubleTypeMapping" /> class.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="dbType"> The <see cref="DbType" /> to be used. </param>
        public OracleDoubleTypeMapping(
            [NotNull] string dbTypeName,
            [CanBeNull] DbType? dbType = null)
            : base(dbTypeName, typeof(double), dbType)
        {
        }

        /// <summary>
        ///     Creates a copy of this mapping.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
        /// <returns> The newly created mapping. </returns>
        public override TypeMapping Clone(string dbTypeName, int? size)
        {
            return new OracleDoubleTypeMapping(dbTypeName, this.DbType);
        }

        /// <summary>
        ///     Generates the SQL representation of a literal value.
        /// </summary>
        /// <param name="value">The literal value.</param>
        /// <returns>
        ///     The generated string.
        /// </returns>
        protected override string GenerateNonNullSqlLiteral(object value)
        {
            var literal = base.GenerateNonNullSqlLiteral(value);

            if (!literal.Contains("E")
                && !literal.Contains("e"))
            {
                return literal + "E0";
            }

            return literal;
        }

        protected override bool IsAssignable(Type modelType, Type dbType)
        {
            return base.IsAssignable(modelType, dbType) || modelType == typeof(decimal);
        }

        protected override void ConfigureParameter([NotNull] DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            base.ConfigureParameter(parameter, adoDbParameter);

            if ("binary_double".Equals(this.DbTypeName, StringComparison.OrdinalIgnoreCase) 
                && parameter is OracleParameter oracleParameter)
            {
                oracleParameter.OracleDbType = OracleDbType.BinaryDouble;
            }
        }
    }
}
